import { FC, useRef, useEffect, memo } from 'react'
import { Modal, Form, TreeSelect, DatePicker, message } from 'antd'
import type { FormInstance } from 'antd'
import { connect, EvaluationStateType, Dispatch } from 'umi'
import moment, { Moment } from 'moment'

interface IProps {
  dispatch: Dispatch
  visible: boolean
  hide: () => any
  code: string
  evaluationModel: EvaluationStateType
  update: () => any
}

interface FormValues {
  [name: string]: any
}
const { TreeNode } = TreeSelect
const AddWarningPage: FC<IProps> = ({
  visible,
  hide,
  code,
  evaluationModel,
  dispatch,
  update
}) => {
  const { unitList } = evaluationModel
  const formRef = useRef<FormInstance>(null)
  const handleOk = () => {
    formRef.current?.submit()
  }
  const handleCancel = () => {
    formRef.current?.resetFields()
    hide()
  }

  // 限制当天之前的日期不可选
  const disabledDate = (current: Moment) => {
    return current && current < moment().subtract(1, 'days') //当天之前的不可选，不包括当天
    //return current && current < moment().endOf("day");当天之前的不可选，包括当天
  }

  const renderTree = (data: any[]) => {
    return data.map((item) => {
      if (item.children?.length) {
        return (
          <TreeNode value={item.code} title={item.name} key={item.code}>
            {renderTree(item.children)}
          </TreeNode>
        )
      } else {
        return (
          <TreeNode
            value={item.code}
            title={item.name}
            key={item.code}
          ></TreeNode>
        )
      }
    })
  }
  const onFinish = (values: FormValues) => {
    dispatch({
      type: 'evaluationModel/function_addBatchWarningInfo',
      payload: {
        ...values,
        code,
        WarningTime: moment(values.WarningTime)
          .add(30, 'm')
          .format('YYYY-MM-DD HH:mm:ss'),
        unitCode: values.unitCode.map((item: any) => item.value).join(','),
        content: values.content.format('YYYY-MM-DD')
      },
      callback: (response) => {
        if (response.code === 200) {
          message.success('新增成功')
          handleCancel()
          update()
        }
      }
    })
  }
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo)
  }

  // 查询机构
  const getUnitInfo = () => {
    dispatch({
      type: 'evaluationModel/function_getUnitInfo',
      payload: {}
    })
  }

  useEffect(() => {
    if (!visible) return
    getUnitInfo()
  }, [visible])
  return (
    <>
      <Modal
        title="新增评价预警信息"
        open={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        width="1000px"
        okText="确认"
        cancelText="取消"
      >
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          ref={formRef}
        >
          <Form.Item
            label="参与机构"
            name="unitCode"
            rules={[{ required: true, message: '请选择机构!' }]}
          >
            <TreeSelect
              placeholder="请选择参与机构"
              multiple
              showCheckedStrategy={TreeSelect.SHOW_ALL}
              treeCheckable
              treeDefaultExpandAll
              treeCheckStrictly
            >
              {renderTree(unitList)}
            </TreeSelect>
          </Form.Item>
          <Form.Item
            label="发送预警时间"
            name="WarningTime"
            rules={[{ required: true, message: '请选择预警时间!' }]}
          >
            <DatePicker
              placeholder="请选择预警时间"
              showTime
              disabledDate={disabledDate}
            />
          </Form.Item>

          <Form.Item
            label="评价截止日期"
            name="content"
            rules={[{ required: true, message: '评价截止日期!' }]}
          >
            <DatePicker
              placeholder="请选择评价截止日期"
              disabledDate={disabledDate}
            />
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}

const mapStateToProps = ({
  evaluationModel
}: {
  evaluationModel: EvaluationStateType
}) => {
  return {
    evaluationModel
  }
}

export default connect(mapStateToProps)(memo(AddWarningPage))
